<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admins;
use App\Models\Users;
use Carbon\Carbon;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Mews\Captcha\Facades\Captcha;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    public function __construct()
    {
//        $this->middleware('guest:admin', ['except' => 'logout']);
    }

    public function login(Request $request){
        if($request->method() == 'POST'){
            $data = $request->all();
            $rules = [
                'username' => 'required|exists:admins,username,status,1',
                'password' => 'required',
                'captcha'  => 'required|captcha'
            ];
            $msgs = [
                'username.required' => '请填写管理员账号',
                'username.exists'   => '管理员账号不存在或者账户被锁定,请联系超级管理员',
                'password.required' => '请填写管理员密码',
                'captcha.required'  => '请填写验证码',
                'captcha.captcha'   => '验证码错误',
            ];
            $validator = validator()->make($data,$rules,$msgs);
            if ($validator->fails()) {
                return $this->writeJson(1,null,$validator->errors()->first());
            }
            if (auth()->guard('admin')->attempt(['username' => $data['username'],'password' => $data['password']])) {
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                return $this->writeJson(0,route('admin.index.index'),'登录成功，页面即将跳转...');
            }
            return $this->writeJson(1,null,'密码输入错误');
        }else{
            return view('admin.auth.login');
        }
    }

    public function captcha()
    {
        return $this->writeJson(0,captcha_src());
    }


    public function logout(Request $request)
    {
        auth()->guard('admin')->logout();
        $request->session()->regenerate();
        return redirect(route('admin.auth.login'));
    }



}